package com.atbeijing.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtil {

    /**
     * 秒级时间戳转日期
     * @param timestamp
     * @return "yyyy-MM-dd HH:mm:ss"
     */
    public static String secondTimestampToDate (Long timestamp){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneOffset.ofHours(8));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(dateTimeFormatter);
    }

    /**
     * 毫秒级时间戳转日期
     * @param timestamp
     * @return "yyyy-MM-dd HH:mm:ss"
     */
    public static String milliTimestampToDate (Long timestamp){
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.ofHours(8));
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(dateTimeFormatter);
    }

    /**
     * 获取当前时间
     * @return "yyyy-MM-dd HH:mm:ss"
     */
    public static String getStrTime (){
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = localDateTime.format(dateTimeFormatter);
        return format;
    }

    /**
     * 字符串日期转东八区毫秒级时间戳
     * @param date "yyyy-MM-dd HH:mm:ss"
     * @return
     */
    public static long dateToTimestamp(String date){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(date, dateTimeFormatter);
        return parse.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }
}
